<?php
declare(strict_types=1);

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

class OssFile extends Model
{
    use SoftDelete;
    
    protected $name = 'oss_file';
    protected $pk = 'id';
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    
    // 类型转换
    protected $type = [
        'file_size' => 'integer',
    ];

    // 自动JSON序列化字段
    protected $json = ['extend'];
    protected $jsonAssoc = true;
    
    // 追加属性
    protected $append = [
        'size_format',
        'uploader_info'
    ];

    // 自动写入上传时间
    protected $insert = ['upload_time'];
    
    /**
     * 上传时间自动完成
     */
    protected function setUploadTimeAttr()
    {
        return time();
    }
    
    /**
     * 获取格式化后的文件大小
     */
    public function getSizeFormatAttr($value, $data)
    {
        $size = $data['file_size'];
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        
        for ($i = 0; $size >= 1024 && $i < 4; $i++) {
            $size /= 1024;
        }
        
        return round($size, 2) . ' ' . $units[$i];
    }
    
    /**
     * 获取上传者信息
     */
    public function getUploaderInfoAttr($value, $data)
    {
        $extend = $this->getAttr('extend') ?: [];
        
        if (!empty($extend['uploader'])) {
            return [
                'type' => $extend['uploader']['type'] ?? '',
                'id' => $extend['uploader']['id'] ?? 0,
                'name' => $extend['uploader']['name'] ?? '未知用户'
            ];
        }
        
        return null;
    }
    
    /**
     * 保存文件记录
     * @param array $data 文件数据
     * @param array $uploader 上传者信息 ['type' => 'admin|user', 'id' => 1, 'name' => '管理员']
     * @param array $extend 其他扩展数据
     * @return bool
     */
    public function saveFile(array $data, array $uploader, array $extend = []): bool
    {
        // 合并扩展信息
        $data['extend'] = array_merge($extend, [
            'uploader' => $uploader,
            'module' => $extend['module'] ?? '',
            'purpose' => $extend['purpose'] ?? '',
            'remark' => $extend['remark'] ?? '',
            'tags' => $extend['tags'] ?? [],
            'related_id' => $extend['related_id'] ?? 0
        ]);
        
        return $this->save($data);
    }
    
    /**
     * 获取文件列表
     * @param array $where 查询条件
     * @param int $pageNo 页码
     * @param int $pageSize 每页数量
     * @return \think\Paginator
     */
    public function getFileList(array $where = [], int $pageNo = 1, int $pageSize = 10)
    {
        return $this->where($where)
            ->order('upload_time', 'desc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $pageNo
            ]);
    }
}